window.config = {
        app_version: '1.0.0',
        web_path: 'http://zm.weihankeji.com/', //网页地址
        dev_path: 'http://zm.weihankeji.com/', //接口地址
        max_time: 1000,
        ajax_timeout: 30,
        debug: false,
        pagelimt: 20,
    }
    // ------------------------------------------------------------------
    // ------------------------------------------------------------------
    // 通用
    // ------------------------------------------------------------------
    // ------------------------------------------------------------------
    //下拉刷新
function fnInitPullRefresh(cbk) {
    api.setRefreshHeaderInfo({
        visible: true,
        loadingImg: 'widget://image/refresh.png',
        bgColor: '#f0f0f0',
        textColor: '#888',
        textDown: '下拉刷新...',
        textUp: '松开刷新...',
        showTime: false
    }, function(ret, err) {
        cbk(ret)
    });
};

//上滑加载
function fnInitScrollToBottom(cbk) {
    api.addEventListener({
        name: 'scrolltobottom',
        extra: {
            threshold: 55 //设置距离底部多少距离时触发，默认值为0，数字类型
        }
    }, function(ret, err) {
        cbk(ret)
    });
};
//退出事件监听
function keyback() {
    var keyback_num = 0;
    api.addEventListener({
        name: 'keyback'
    }, function(ret, err) {
        if (keyback_num) {
            api.closeWidget({
                silent: true
            })
        }
        setTimeout(function() {
            keyback_num = 0;
        }, 2000)
        toast('再按一次退出应用')
        keyback_num++;
    });
}

function fnDelay(cbk, time) {
    setTimeout(function() {
        cbk()
    }, time)
}

function delay_close(time) {
    setTimeout(function() {
        close_win()
    }, time)
}
//打开美洽
function openmeiQia() {
    var mq = api.require('meiQia');
    //配置初始化美洽需要的appkey
    var param = {
        appkey: "1d67c877cf6f6d1d8961e27af9dc3a58"
    };
    // alert("mq")
    //初始化美洽
    mq.initMeiQia(param, function(ret, err) {
            if (ret) {
                //初始化成功
                //设置用户信息
                var infoParam = {
                    email: "dev@meiqia.com",
                    comment: "这是备注",
                    avatar: "https://app.meiqia.com/images/logo.png",
                    tags: ["付费用户", "使用疑问"]
                };
                mq.setClientInfo(infoParam);
                mq.show();
                // alert(JSON.stringify(ret));
            } else {
                //初始化失败
                // alert(JSON.stringify(err));
            }
        })
        //mq.show();
}

function send_event(name, value) {
    api.sendEvent({
        name: name,
        extra: value
    });
}

function add_event(name, cbk) {
    // alert(name)
    api.addEventListener({
        name: name
    }, function(ret, err) {
        if (ret) {
            var data = ret.value
            cbk(data)
        }
    });
}

function logJosn(str) {
    console.log(JSON.stringify(str))
}

function log(str) {
    console.log(str)
}
//图片选择
function select_pic(cbk) {
    api.actionSheet({
        cancelTitle: '取消',
        buttons: ['拍照上传', '从相册选择']
    }, function(ret, err) {
        var index = ret.buttonIndex;
        if (index == 1 || index == 2) {
            var sourceType = index == 1 ? 'camera' : 'album';
            api.getPicture({
                sourceType: sourceType,
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'base64',
                quality: 50,
                allowEdit: false,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret) {
                    if (ret.data.length > 0) {
                        cbk(ret)
                            // openImageClipFrame(ret.data);
                    }
                } else {
                    toast(err)
                }
            });
        }
    });
}

//头像图片选择
function select_pic_avater(cbk) {
    api.actionSheet({
        cancelTitle: '取消',
        buttons: ['拍照上传', '从相册选择']
    }, function(ret, err) {
        var index = ret.buttonIndex;
        if (index == 1 || index == 2) {
            var sourceType = index == 1 ? 'camera' : 'album';
            api.getPicture({
                sourceType: sourceType,
                encodingType: 'jpg',
                mediaValue: 'pic',
                destinationType: 'base64',
                quality: 50,
                allowEdit: false,
                saveToPhotoAlbum: false
            }, function(ret, err) {
                if (ret) {
                    if (ret.data.length > 0) {
                        // cbk(ret)
                        openImageClipFrame(ret.data);
                    }
                } else {
                    toast(err)
                }
            });
        }
    });
}

// 打开图片裁剪功能
function openImageClipFrame(img_src) {
    open_win('imageClipFrame', 'widget://html/imageClipFrame.html', false, {
        img_src,
        img_src
    })
}





//图片选择
function get_pic(cbk) {
    api.getPicture({
        sourceType: 'library',
        mediaValue: 'pic',
        destinationType: 'base64',
        allowEdit: true,
        quality: 50,
        saveToPhotoAlbum: false
    }, function(ret, err) {
        if (ret) {
            if (ret.base64Data != '') {
                cbk(ret)
            }
        } else {
            toast(err.msg)
        }
    });
}
//图片多张选择
function select_album(max, cbk) {
    var mediaScanner = api.require('UIMediaScanner');
    mediaScanner.open({
        exchange: true,
        column: 4,
        type: 'picture',
        classify: false,
        max: max,
        sort: {
            key: 'time',
            order: 'desc'
        },
        texts: {
            stateText: '相机胶卷',
            cancelText: '取消',
            finishText: '完成'
        },
        styles: {
            bg: '#fff',
            mark: {
                icon: 'widget://image/icon/icon-aftersale-susses.png',
                position: 'bottom_right',
                size: 30
            },
            nav: {
                bg: '#ffffff',
                stateColor: '#F100FF',
                stateSize: 18,
                cancelBg: 'rgba(0,0,0,0)',
                cancelColor: '#005A93',
                cancelSize: 18,
                finishBg: 'rgba(0,0,0,0)',
                finishColor: '#005A93',
                finishSize: 18
            }
        }
    }, function(ret) {
        if (ret && ret.list.length > 0) {
            var length = ret.list.length;
            for (var i = 0; i < length; i++) {
                mediaScanner.transPath({
                    path: ret.list[i].path
                }, function(ret) {
                    cbk(ret)
                });
            }
        } else {
            mediaScanner.transPath({
                path: ret.path
            }, function(ret) {
                cbk(ret)
            });
        }
    });
}


function compress_pic(path, cbk) {
    var imageFilter = api.require('imageFilter');
    imageFilter.compress({
        img: path,
        quality: 1,
        size: {
            w: 50,
            h: 50
        },
        save: {
            imgPath: 'widget://share/',
            imgName: 'share.png'
        }
    }, function(ret, err) {
        log(JSON.stringify(ret))
        if (ret.status) {
            log(ret.status)
            cbk(ret)
        } else {
            log(JSON.stringify(err));
        }
    });
}
//打开窗口
function open_win(name, url, bounces, param) {
    console.log(param);

    // alert(url)
    var delay = 0;
    if (api.systemType != 'ios') {
        delay = 100;
    }
    api.openWin({
        name: name,
        url: url,
        pageParam: param,
        bounces: bounces,
        delay: delay,
        slidBackEnabled: true,
        vScrollBarEnabled: false,
        animation: {
            type: 'movein',
            subType: "from_right",
            duration: 300
        },
        bgColor: '#fff'
    });
}
//打开页面
function open_frame(name, url, id, bounces, param) {
    var header = $api.byId(id)
    var headerPos = $api.offset(header);
    api.openFrame({
        name: name,
        url: url,
        bounces: bounces,
        pageParam: param,
        rect: {
            x: 0,
            y: headerPos.h,
            w: 'auto',
            h: 'auto'
        },
        vScrollBarEnabled: false,
        bgColor: '#fff'
    })
}

//打开页面(仅展示底部栏)
function open_frame2(name, url, id, bounces) {
    var footer = $api.byId(id)
    var footerPos = $api.offset(footer);
    api.openFrame({
        name: name,
        url: url,
        bounces: bounces,
        rect: {
            x: 0,
            y: 0,
            w: 'auto',
            h: api.winHeight - footerPos.h
        },
        vScrollBarEnabled: false
    })
}

//打开页面
function open_frame_f(name, url, id, id2, bounces) {
    var header = $api.byId(id)
    var headerPos = $api.offset(header);
    var footer = $api.byId(id2)
    var footerPos = $api.offset(footer);
    api.openFrame({
        name: name,
        url: url,
        bounces: bounces,
        rect: {
            x: 0,
            y: headerPos.h,
            w: 'auto',
            h: api.winHeight - headerPos.h - footerPos.h
        },
        vScrollBarEnabled: false
    })
}
//关闭窗口
function close_win() {
    api.closeWin();
}
//关闭窗口
function closeToRoot() {
    api.closeToWin({
        name: 'root'
    });
}

function refreshWinAndFrame(winname, frameName, fun) {
    api.execScript({
        name: winname,
        frameName: frameName,
        script: fun
    });
}

function refreshFrame(frameName, fun) {
    api.execScript({
        frameName: frameName,
        script: fun
    });
}
//关闭frame
function close_frame() {
    api.closeFrame({});
}
//拨打电话
function call(number) {
    api.call({
        number: number
    })
}
//发送短信
function sms(number, txt) {
    var num = [];
    num.push(number)
    api.sms({
        numbers: num,
        text: txt
    })
}
//时间戳倒计时单个
function TimeCountDown(time) {
    var leftTime = time - (Date.parse(new Date()) / 1000);
    if (leftTime < 1) {
        return "0";
    }
    var hours = parseInt(leftTime / 60 / 60, 10); //计算剩余的小时
    var minutes = parseInt(leftTime / 60 % 60, 10); //计算剩余的分钟
    var seconds = parseInt(leftTime % 60, 10); //计算剩余的秒数
    var data = {
        hours: checkTime(hours),
        minutes: checkTime(minutes),
        seconds: checkTime(seconds)
    }
    return data;
}
//时间戳倒计时多个
function TimeCountDowns(time, nowtime) {
    var leftTime = time - nowtime;
    if (leftTime < 1) {
        return "0";
    }
    var hours = parseInt(leftTime / 60 / 60, 10); //计算剩余的小时
    var minutes = parseInt(leftTime / 60 % 60, 10); //计算剩余的分钟
    var seconds = parseInt(leftTime % 60, 10); //计算剩余的秒数
    var data = {
        hours: checkTime(hours),
        minutes: checkTime(minutes),
        seconds: checkTime(seconds)
    }
    return data;
}
//时间戳倒计时多个返回天小时分钟秒
function TimeCountDownfull(time, nowtime) {
    var leftTime = time - nowtime;
    if (leftTime < 1) {
        return "0";
    }
    var days = parseInt(leftTime / 60 / 60 / 24, 10); //计算剩余的天数
    var hours = parseInt(leftTime / 60 / 60 % 24, 10); //计算剩余的小时
    var minutes = parseInt(leftTime / 60 % 60, 10); //计算剩余的分钟
    var seconds = parseInt(leftTime % 60, 10); //计算剩余的秒数
    var data = {
        days: checkTime(days),
        hours: checkTime(hours),
        minutes: checkTime(minutes),
        seconds: checkTime(seconds)
    }
    return data;
}
//将0-9的数字前面加上0，例1变为01
function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function Convert_BD09_To_GCJ02(lat, lon) {
    var x_pi = 3.14159265358979324 * 3000.0 / 180.0;
    var x = parseFloat(lon) - 0.0065;
    var y = parseFloat(lat) - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    var lon = z * Math.cos(theta);
    var lat = z * Math.sin(theta);
    return {
        lat: lat,
        lon: lon
    };
}
// ucs-2转utf-16（将表情图转换为实体字符）
function ucs2_to_utf16(str, clear) {
    var patt = /[\ud800-\udbff][\udc00-\udfff]/g;
    str = str.replace(patt, function(char) {
        if (clear) {
            return '';
        }
        var H, L, code;
        if (char.length === 2) {
            H = char.charCodeAt(0); // 高位
            L = char.charCodeAt(1); // 低位
            code = (H - 0xD800) * 0x400 + 0x10000 + L - 0xDC00;
            return "&#" + code + ";";
        } else {
            return char;
        }
    });
    return str;
}
//判断数组中元素的下标
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};
//判断数组中是否包含该元素
Array.prototype.inArray = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        return true;
    }
    return false;
};
//删除数组中指定的元素
Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};

// 气泡提示 传入loc的位置就以loc的位置为准，否则就在中央
function toast(str, loc) {
    var location = loc ? loc : 'bottom';
    api.toast({
        msg: str,
        duration: 2000,
        location: location,
        global: true
    });
}

// ------------------------------------------------------------------
// ------------------------------------------------------------------
// QQ、微信相关
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 微博登录（绑定）
function login_wb(cbk, error) {
    var sinaWeiBo = api.require('weiboPlus');
    sinaWeiBo.isInstalled(
        function(ret) {
            if (ret.status) {
                sinaWeiBo.auth(function(ret, err) {
                    if (ret.status && cbk) {
                        console.log(ret.userId)
                        cbk(ret);
                    } else {
                        console.log(err.msg);
                    }
                });
            } else {
                toast('当前设备未安装新浪微博客户端');
                error()
            }
        }
    );
}
// QQ登录（绑定）
function login_qq(cbk, error) {
    var obj_qq = api.require('QQPlus');
    obj_qq.installed(function(ret, err) {
        if (ret.status) {
            obj_qq.login(function(ret, err) {
                if (ret.status && cbk) {
                    console.log(ret.openId)
                    cbk(ret);
                } else {
                    console.log(err.msg);
                }
            });
        } else {
            toast('当前设备未安装QQ客户端');
            error(err)
        }
    });
}

// 微信登录（绑定）
function login_wechat(cbk, error) {
    var obj_wx = api.require('wxPlus');
    obj_wx.isInstalled(function(ret, err) {
        if (ret.installed) {
            obj_wx.auth({}, function(ret, err) {
                if (ret.status) {
                    obj_wx.getToken({
                        code: ret.code
                    }, function(ret, err) {
                        if (ret.status && cbk) {
                            cbk(ret);
                        } else {
                            var code = err.code;
                            if (code == -1) {
                                toast('未知错误');
                            } else if (code == 4) {
                                toast('网络超时');
                            } else {
                                toast('登录失败');
                            }
                        }
                    });
                } else if (error) {
                    console.log(err.code);
                }
            });
        } else {
            toast('当前设备未安装微信客户端');
            error(err)
        }
    });
}

// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 与服务器数据交互
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 上拉加载数据交互
function get_data_updown(url, data, cbk, showprogress) {
    // if (showprogress != false) {
    //     api.showProgress({
    //         title: '正在加载...'
    //     });
    // }
    if (window.config.debug) {
        console.log(url + ',' + JSON.stringify(data))
    }
    api.ajax({
        url: window.config.dev_path + url,
        method: 'post',
        timeout: window.config.ajax_timeout,
        data: {
            values: data
        }
    }, function(ret, err) {
        // api.hideProgress();
        api.refreshHeaderLoadDone();
        if (ret) {
            if (window.config.debug) {
                console.log(url + ',(返回数据)' + JSON.stringify(ret))
            }
            if (ret.status == '-1') {
                $api.rmStorage('token');
                $api.rmStorage('userinfo');
                send_event('loginout')
                if (api.frameName != 'my') {
                    toast(ret.msg);
                    setTimeout(function() {
                        openWin_login()
                    }, 300)
                }
                if (api.winName == 'create_order') {
                    setTimeout(function() {
                        close_win()
                    }, 1000)
                }
            } else {
                cbk(ret)
            }
        } else {
            if (window.config.debug) {
                console.log(url + ',(出错信息)' + JSON.stringify(err))
            }
            toast('网络不稳定')
        }
    });
}

function get_data(url, data, cbk, showprogress) {
    if (showprogress != false) {
        // api.showProgress({
        //     title: '正在加载...'
        // });
        var activity = api.require('UILoading');
        activity.keyFrame({
            rect: {
                w: 80,
                h: 80
            },
            styles: {
                bg: 'rgba(0,0,0,0)',
                corner: 5,
                interval: 50,
                frame: {
                    w: 80,
                    h: 80
                }
            },
            content: [{
                    frame: 'widget://image/refresh/1.png'
                }, {
                    frame: 'widget://image/refresh/2.png'
                }, {
                    frame: 'widget://image/refresh/3.png'
                }, {
                    frame: 'widget://image/refresh/4.png'
                }, {
                    frame: 'widget://image/refresh/5.png'
                }, {
                    frame: 'widget://image/refresh/6.png'
                }, {
                    frame: 'widget://image/refresh/7.png'
                }, {
                    frame: 'widget://image/refresh/8.png'
                }, {
                    frame: 'widget://image/refresh/9.png'
                }, {
                    frame: 'widget://image/refresh/10.png'
                }, {
                    frame: 'widget://image/refresh/11.png'
                }, {
                    frame: 'widget://image/refresh/12.png'
                }, {
                    frame: 'widget://image/refresh/13.png'
                }, {
                    frame: 'widget://image/refresh/14.png'
                }, {
                    frame: 'widget://image/refresh/15.png'
                }, {
                    frame: 'widget://image/refresh/16.png'
                }, {
                    frame: 'widget://image/refresh/17.png'
                }, {
                    frame: 'widget://image/refresh/18.png'
                }, {
                    frame: 'widget://image/refresh/19.png'
                }, {
                    frame: 'widget://image/refresh/20.png'
                }, {
                    frame: 'widget://image/refresh/21.png'
                }, {
                    frame: 'widget://image/refresh/22.png'
                }, {
                    frame: 'widget://image/refresh/23.png'
                }, {
                    frame: 'widget://image/refresh/24.png'
                }, {
                    frame: 'widget://image/refresh/25.png'
                }

            ],
        });
    }
    if (window.config.debug) {
        console.log(url + ',' + JSON.stringify(data))
    }
    api.ajax({
        url: window.config.dev_path + url,
        method: 'post',
        timeout: window.config.ajax_timeout,
        data: {
            values: data
        }
    }, function(ret, err) {
        console.log(JSON.stringify(ret))
        var uiloading = api.require('UILoading');
        uiloading.closeKeyFrame();
        // api.hideProgress();
        api.refreshHeaderLoadDone();
        if (ret) {
            if (window.config.debug) {
                console.log(url + ',(返回数据)' + JSON.stringify(ret))
            }
            if (ret.status == '-1') {
                $api.rmStorage('token');
                $api.rmStorage('userinfo');
                send_event('loginout')
                if (api.frameName != 'my') {
                    toast(ret.msg);
                    setTimeout(function() {
                        openWin_login()
                    }, 300)
                }
                if (api.winName == 'create_order') {
                    setTimeout(function() {
                        close_win()
                    }, 1000)
                }
            } else {
                cbk(ret)
            }
        } else {
            if (window.config.debug) {
                console.log(url + ',(出错信息)' + JSON.stringify(err))
            }
            // toast('网络不稳定')
        }
    });
}
//从服务器获取用户信息
function getuserinfo() {
    // alert(1)
    get_data('api/user/getUserInfo', {
        token: $api.getStorage('token')
    }, function(ret) {
		// alert(JSON.stringify(ret));
        if (ret.status == 1) {
            save_userinfo_new(ret)
                //获取未读消息数目
            if (ret.data.msg_count != 0) {
                api.sendEvent({
                    name: 'noReadCount',
                    extra: {
                        count: ret.data.msg_count
                    }
                });
            }
        } else {
            $api.rmStorage('token'); //清除token
            $api.rmStorage('userinfo'); //清除用户信息
        }
    }, false)
}

function get_data_allurl(url, data, cbk) {
    api.showProgress({
        title: '正在加载...'
    });
    api.ajax({
        url: url,
        method: 'post',
        timeout: window.config.ajax_timeout,
        data: {
            values: data
        }
    }, function(ret, err) {
        api.hideProgress();
        api.refreshHeaderLoadDone();
        if (ret) {
            if (window.config.debug) {
                console.log(url + ',(返回数据)' + JSON.stringify(ret))
            }
            cbk(ret)
        } else {
            if (window.config.debug) {
                console.log(JSON.stringify(err))
            }
            toast('网络不稳定')
        }
    });
}

function post_img(url, data, cbk) {
    if (window.config.debug) {
        console.log('上传图片：' + url + ',' + JSON.stringify(data))
    }
    api.ajax({
        url: window.config.dev_path + url,
        method: 'post',
        timeout: window.config.ajax_timeout,
        data: {
            files: {
                file: data
            }
        }
    }, function(ret, err) {
        if (ret) {
            if (window.config.debug) {
                console.log(url + ',(返回数据)' + JSON.stringify(ret))
            }
            cbk(ret)
        } else {
            api.hideProgress();
            if (window.config.debug) {
                console.log(JSON.stringify(err))
            }
        }
    });
}

function post_ava(url, data, cbk) {
    if (window.config.debug) {
        console.log('上传头像：' + url + ',' + JSON.stringify(data))
    }
    api.ajax({
        url: window.config.dev_path + url,
        method: 'post',
        timeout: window.config.ajax_timeout,
        data: {
            values: {
                token: $api.getStorage('token')
            },
            files: {
                file: data
            }
        }
    }, function(ret, err) {
        if (ret) {
            if (window.config.debug) {
                console.log(url + ',(返回数据)' + JSON.stringify(ret))
            }
            cbk(ret)
        } else {
            api.hideProgress();
            if (window.config.debug) {
                console.log(JSON.stringify(err))
            }
            toast('网络不稳定')
        }
    });
}
//{
//	fileSize: 0, //文件大小，数字类型
//	percent: 0, //下载进度（0-100），数字类型
//	state: 0, //下载状态，数字类型。（0：下载中、1：下载完成、2：下载失败）
//	savePath: '' //存储路径（字符串类型）
//		}
function download(url, cbk) {
    console.log(url)
    api.download({
        url: url,
        //savePath:'fs://',
        allowResume: true
    }, function(ret, err) {
        console.log(JSON.stringify(ret))
        if (ret.state == 1) {
            log(ret.fileSize)
            cbk(ret.savePath)
        }
    });
}
//存储用户信息
function save_userinfo_new(ret) {
    $api.setStorage('userinfo', ret.data)
}

//点赞收藏接口
//source [数据类型（xx孝讯文章，xx_reply孝讯评论，xyx会员秀，xyx_reply会员秀评论，good商品，good_comment商品评论）]
//type	True	int	交互类型(1点赞，2收藏，3转发)

function opera(id, source, type, cbk) {
    if ($api.getStorage('token')) {
        get_data('api/opera/opera', {
            token: $api.getStorage('token'),
            data_id: id,
            source: source,
            type: type
        }, function(ret) {
            cbk(ret)
        })
    } else {
        toast('请登录')
        openWin_login()
    }
}
//子评论点赞
function opera_children(id, source, type, cbk) {
    if ($api.getStorage('token')) {
        get_data('api/opera/opera', {
            token: $api.getStorage('token'),
            data_id: id,
            source: source,
            type: type
        }, function(ret) {
            cbk(ret)
        })
    } else {
        toast('请登录')
        openWin_login()
    }
}
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 创建新页面
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// 打开登录页面
function openWin_login() {
    open_win('login', 'widget://html/login/login.html', false)
}
// 打开绑定页面
function openWin_bind() {
    open_win('bind', 'widget://html/login/bind.html', false)
}
// 打开修改密码页面
function openWin_edit_pwd() {
    open_win('edit_pwd', 'widget://html/login/edit_pwd.html', false)
}
// 打开搜索页面
function openWin_Search() {
    open_win('search', 'widget://html/search/search.html', false)
}
// 打开商品详情页面
function openWin_goods_detail(id, miao_id, time_id, is_remind_new, soon_time) {
    $api.setStorage('id', id)
    $api.setStorage('miao_id', miao_id)
    $api.setStorage('time_id', time_id)
    $api.setStorage('is_remind_new', is_remind_new)
    $api.setStorage('soon_time', soon_time)
    open_win('goods_detail', 'widget://html/goods/goods_detail.html', false, {
        id: id
    })
}

// 打开商品详情页面
function openWin_score_detail(id) {
    $api.setStorage('id', id)
    open_win('score_detail', 'widget://html/goods/score_detail.html', false, {
        id: id
    })
}


// 打开未开始秒杀商品详情页面
function openWin_goods_detail_miao(id, miao_id, time_id, miao_start_time) {
    $api.setStorage('id', id)
    $api.setStorage('miao_id', miao_id)
    $api.setStorage('time_id', time_id)
    $api.setStorage('miao_start_time', miao_start_time)
    open_win('goods_detail_miao', 'widget://html/goods/goods_detail_miao.html', false)
}
// 打开拼团详情页面
function openWin_pintuan_details(id) {
    $api.setStorage('id', id)
    open_win('pintuan_details', 'widget://html/my/order/pintuan_details.html', false)
}
// 打开全部拼团页面
function openWin_group_all_join(act_id, good_id) {
    $api.setStorage('tuan_id', act_id)
    $api.setStorage('good_id', good_id)
    open_win('group_all_join', 'widget://html/goods/group_all_join.html', false)
}
// 打开商品分类型列表页面
function openWin_goods_list_type(sign) {
    $api.setStorage('sign', sign)
    if (sign == "限时") {
        open_win('good_limited_price', 'widget://html/goods/good_limited_price.html', false)
    } else if (sign == "最近订购") {
        open_win('good_recent', 'widget://html/goods/good_recent.html', false)
    } else {
        open_win('goods_list_type', 'widget://html/goods/goods_list_type.html', false)
    }

}

// 打开生成订单页面
function openWin_create_order() {
    open_win('create_order', 'widget://html/cart/create_order.html', false)
}

// 打开生成订单页面
function openWin_create_score() {
    open_win('create_score', 'widget://html/cart/create_score.html', false)
}


// 打开我的订单页面
function openWin_order_list(status) {
    $api.setStorage('status', status)
    if (status == "all") {
        open_win('order_all', 'widget://html/my/order/order_all.html', false)
    } else {
        open_win('order', 'widget://html/my/order/order.html', false)
    }

}

// 打开我的订单页面
function openWin_score_order_list(status) {
    $api.setStorage('status', status)
    if (status == "all") {
        open_win('order_all', 'widget://html/my/order/score_order_all.html', false)
    } else {
        open_win('order', 'widget://html/my/order/score_order.html', false)
    }

}
// 打开订单详情页面
function openWin_order_detail(id) {
    $api.setStorage('id', id)
    open_win('order_detail', 'widget://html/my/order/order_detail.html', false)
}

// 打开订单详情页面
function openWin_score_order_detail(id) {
    $api.setStorage('id', id)
    open_win('score_order_detail', 'widget://html/my/order/score_order_detail.html', false)
}



// 打开订单详情页面
function openWin_logistics_detail(id) {
    $api.setStorage('id', id)
    open_win('logistics_detail', 'widget://html/my/order/logistics_detail.html', false)
}
// 打开提交售后页面
function openWin_order_aftersale(id, order_id) {
    console.log(id);

    $api.setStorage('aftersale', id)
    $api.setStorage('order_id', order_id)
    open_win('aftersale_apply', 'widget://html/my/order/aftersale_apply.html', false)
}
// 打开售后详情页面
function openWin_aftersale_detail(id) {
    console.log(id);

    $api.setStorage('id', id)
    open_win('aftersale_detail', 'widget://html/my/order/aftersale_detail.html', false)
}
// 打开团购商品详情页面
function openWin_group_goods_detail() {
    open_win('group_goods_detail', 'widget://html/goods/group_goods_detail.html', false)
}
// 打开秒杀商品详情页面
function openWin_miaosha_goods_detail() {
    open_win('miaosha_goods_detail', 'widget://html/goods/miaosha_goods_detail.html', false)
}
// 打开消息页面
function openWin_message() {
    open_win('my_message', 'widget://html/my/my_message.html', false)
}
// 打开会员秀详情页面
function openWin_circle_details(id, status, index) {
    $api.setStorage('id', id)
    $api.setStorage('status', status)
    $api.setStorage('index', index)
        // alert(index)
    open_win('circle_details', 'widget://html/circle/circle_details.html', false)
}
// 打开会员秀详情页面审核中
function openWin_circle_details_wsh(id) {
    $api.setStorage('id', id)
    open_win('circle_details_wsh', 'widget://html/circle/circle_details_wsh.html', false)
}
// 打开我的会员秀详情页面审核成功
function openWin_circle_details_my(id) {
    $api.setStorage('id', id)
    open_win('circle_details_my', 'widget://html/circle/circle_details_my.html', false)
}
// 打开我的会员秀详情页面审核失败
function openWin_circle_details_false(id) {
    $api.setStorage('id', id)
    open_win('circle_details_false', 'widget://html/circle/circle_details_false.html', false)
}
// 打开会员秀编辑页面
function openWin_publish_edit(id) {
    $api.setStorage('id', id)
    open_win('publish_edit', 'widget://html/my/publish/publish_edit.html', false)
}
// 打开会员秀全部评价页面
function openWin_circle_comment(index, id, catid, comment_id) {
    $api.setStorage('index', index);
    $api.setStorage('id', id)
    $api.setStorage('catid', catid)
    $api.setStorage('comment_id', comment_id);
    open_win('circle_comment', 'widget://html/circle/circle_comment.html', false)
}

function openWin_circle_allcomment(index, article_id) {
    $api.setStorage('index', index);
    $api.setStorage('article_id', article_id);
    open_win('circle_comment', 'widget://html/circle/circle_comment_all.html', false)
}
// 打开单页详情页面
function open_win_page(title) {
    $api.setStorage('title', title)
    open_win('page', 'widget://html/page/page.html', false)
}
// 打开消息详情页面
function openWin_message_details(id) {
    $api.setStorage('id', id)
    open_win('my_message_detail', 'widget://html/my/my_message_detail.html', false)
}
// 打开订单详情页面
function openWin_order_details(id) {
    $api.setStorage('id', id)
    open_win('order_detail', 'widget://html/my/order/order_detail.html', false)
}
// 打开外部链接
function openWin_url(url) {

    if (url == '') {
        //		toast('网络不稳定','bottom');
        return;
    } else {

        // 打开外部链接
        api.openWin({
            useWKWebView: true,
            name: 'browser',
            url: 'widget://html/browser.html',
            bounces: false,
            pageParam: {
                url: url,
                name: '链接'
            }
        });
        // var browser = api.require('webBrowser');
        // browser.open({
        //     url: url
        // });
    }
    // $api.setStorage('weburl', url)
    // api.openWin({
    //     name: 'webBrowser',
    //     url: 'widget://html/webBrowser/webBrowser.html',
    //     bounces: false,
    //     vScrollBarEnabled: false,
    //     hScrollBarEnabled: false,
    //     slidBackEnabled: true,
    //     animation: {
    //         type: 'fade',
    //         duration: 300
    //     }
    // });
}
//
function openbanner(vo) {
    //	无链接有广告内容
    if (vo.flag == 1) {
        $api.setStorage('banner_content', vo)
        open_win('banner', 'widget://html/page/banner.html', false)
    }
    //	外链接
    if (vo.flag == 2) {
        openWin_url(vo.url)
    }
    //	商品链接
    if (vo.flag == 3) {
        openWin_goods_detail(vo.url)
    }
    //	秒杀
    if (vo.flag == 4) {
        open_win('miaosha_goods_list', 'widget://html/goods/miaosha_goods_list.html', false)
    }
    //	团购
    if (vo.flag == 5) {
        open_win('group_goods_list', 'widget://html/goods/group_goods_list.html', false)
    }
    //	资讯	会员秀
    if (vo.flag == 6 || vo.flag == 7) {
        openWin_circle_details(vo.url)
    }
}





function closeWin() {
    api.closeWin();
}
// 打开新页面
function openWin(url, pageParam) {
    api.openWin({
        name: url,
        url: 'widget://html/' + url + '.html',
        pageParam: pageParam,
        animation: {
            duration: 200,
            type: "push", //动画类型（详见动画类型常量）
            subType: "from_right",
        },
        bounces: false,
        bgColor: '#ffffff',
        vScrollBarEnabled: true,
        hScrollBarEnabled: false,
        reload: true,
        delay: 0,
    });
}

// 判断权限是否存在 返回类型 布尔值 如果有权限,就直接执行,如果没有权限就获取权限
function getHasPermission(key, callback) {
    // 对照列表
    var codeList = {
        'camera': '相机',
        'contacts': '联系人读取',
        'contacts-r': '仅联系人读取',
        'contacts-w': '仅联系人写入',
        'microphone': '麦克风',
        'photos': '访问相册',
        'location': '定位',
        'locationAlways': '后台定位',
        'notification': '状态栏通知',
        'calendar': '日历读取/写入',
        'calendar-r': '仅日历读取',
        'calendar-w': '仅日历写入',
        'phone': '拨打电话',
        'phone-call': '仅直接拨打电话',
        'phone-r': '仅获取手机号码',
        'phone-r-log': '读取通话记录',
        'phone-w-log': '写入通话记录',
        'sensor': '传感器',
        'sms': '读取短信/后台发送短信',
        'sms-s': '仅后台发送短信',
        'sms-r': '仅读取短信',
        'storage': '读写',
        'storage-r': '写入',
        'storage-w': '读取',
    }
    var list = [];
    list.push(key);
    var result = api.hasPermission({
        list: list
    });
    if (result[0].granted) {
        callback(true);
    } else {
        //api.systemType == "ios" && 
        if (result[0].undetermined) {
            callback(true);
        } else {
            api.confirm({
                title: '提醒',
                msg: '没有获得 ' + codeList[result[0].name] + " 权限\n是否前往设置？",
                buttons: ['去设置', '取消']
            }, function(ret, err) {
                if (1 === ret.buttonIndex) {
                    api.requestPermission({
                        list: list,
                        code: 100001
                    }, function(ret, err) {
                        callback(ret.list[0].granted);
                    });
                } else {
                    callback(false);
                }
            });
        }
    }
}

//刷新 更改

function refresh_new(cbk) {
    api.setCustomRefreshHeaderInfo({
        bgColor: '#FFFFFF',
        isScale: true,
        loadAnimInterval: 50,
        image: {
            pull: [
                'widget://image/refresh/1.png',
                'widget://image/refresh/2.png',
                'widget://image/refresh/3.png',
                'widget://image/refresh/4.png',
                'widget://image/refresh/5.png',
                'widget://image/refresh/6.png',
                'widget://image/refresh/7.png',
                'widget://image/refresh/8.png',
                'widget://image/refresh/9.png',
                'widget://image/refresh/10.png',
                'widget://image/refresh/11.png',
                'widget://image/refresh/12.png',
                'widget://image/refresh/13.png',
                'widget://image/refresh/15.png',
                'widget://image/refresh/16.png',
                'widget://image/refresh/17.png',
                'widget://image/refresh/18.png',
                'widget://image/refresh/19.png',
                'widget://image/refresh/20.png',
                'widget://image/refresh/21.png',
                'widget://image/refresh/22.png'
            ],
            load: [
                'widget://image/refresh/1.png',
                'widget://image/refresh/2.png',
                'widget://image/refresh/3.png',
                'widget://image/refresh/4.png',
                'widget://image/refresh/5.png',
                'widget://image/refresh/6.png',
                'widget://image/refresh/7.png',
                'widget://image/refresh/8.png',
                'widget://image/refresh/9.png',
                'widget://image/refresh/10.png',
                'widget://image/refresh/11.png',
                'widget://image/refresh/12.png',
                'widget://image/refresh/13.png',
                'widget://image/refresh/14.png',
                'widget://image/refresh/15.png',
                'widget://image/refresh/16.png',
                'widget://image/refresh/17.png',
                'widget://image/refresh/18.png',
                'widget://image/refresh/19.png',
                'widget://image/refresh/20.png',
                'widget://image/refresh/21.png',
                'widget://image/refresh/22.png'
            ]
        }
    }, function(ret, err) {
        cbk(ret)
    });
}


// 获取定位,如果单位成功返回成功值,如果定位失败,就返回失败消息
function localcity(callback) {
    // 获取储存的城市
    var localcity = api.getPrefs({
        sync: true,
        key: 'localcity'
    });
    // 如果本地有城市信息
    if (localcity) {
        localcity = JSON.parse(localcity);
        // localcity.lon && localcity.lat &&
        if (localcity.id) {
          if(typeof callback === "function"){
            callback(localcity)
          }
        } else {
            getLocal(function(ret, err) {
                if (ret) {
                  if(typeof callback === "function"){
                    callback(ret)
                  }
                } else {
                  if(typeof callback === "function"){
                    callback({}, err)
                  }
                }
            })
        }
    } else {
        getLocal(function(ret, err) {
            if (ret) {
                callback(ret)
            } else {
                callback({}, err)
            }
        })
    }
}

function getLocal(callback) {
  getHasPermission('location', function(ret) {

      if (ret) {
          var aMapLBS = api.require('aMapLBS');
          aMapLBS.configManager({
              accuracy: 'hundredMeters',
              filter: 1
          }, function(ret, err) {
              if (ret.status) {
                  var aMapLBS = api.require('aMapLBS');
                  aMapLBS.singleAddress({
                      timeout: 10
                  }, function(ret, err) {
                        // alert(JSON.stringify(ret.address.district))
                      if (ret.status) {
                          // var lon = ret.lon;
                          // var lat = ret.lat;
                          // let params = {
                          //     "lon": lon,
                          //     "lat": lat
                          // }
                          let params = {
                              city:ret.address.city,
                              region:ret.address.district
                          }
                          get_data('api/home/locationCity', params, function(res) {
                            // alert(JSON.stringify(res))
                              if (res.status == 1) {
                                  var data = res.data;
                                  // data.lon = lon;
                                  // data.lat = lat;
                                  api.setPrefs({
                                      key: 'localcity',
                                      value: data
                                  });
                                  callback(data)
                              } else {
                                  callback({}, '定位失败')
                              }
                          })
                      } else {
                          callback({}, '定位失败')
                      }
                  });
              }
          });

      } else {
          var lon = 0;
          var lat = 0;
          let params = {
              lon: lon,
              lat: lat
          };
          post_data('api/home/locationCity', params, function(res) {
              if (res.status == 200) {
                  var data = res.data;
                  data.lon = lon;
                  data.lat = lat;
                  api.setPrefs({
                      key: 'localcity',
                      value: data
                  });
                  callback(data)
              } else {
                  callback({}, '定位失败')
              }
          })
      }
  })
}
